require('../db');
const { query } = require('../db/connection/mysql');
const handleRequestPayload = require('../utils/handleRequestPayload');

const UserService_mongodb = {};

const CommonService_mysql = {
	/**
	 * 获取指定数据表的数据总数
	 * @param {String} name 数据表名称
	 * @param {Object} data 请求参数
	 * @returns {Promise<{data: any, fields: string[], message: string, error: boolean}>} result - 数据对象
	 *   - data: 响应数据
	 *   - fields: 数据表字段名数组
	 *   - message: 响应消息
	 *   - error: 是否报错
	 */
	getTotal: async (name, data) => {
		const { current, size, ...filters } = data;
		const { sqlParams, valueList } = handleRequestPayload.query(filters);

		const sql = `SELECT COUNT(*) AS total FROM ${name} WHERE ${sqlParams}`;
		return await query(sql, valueList);
	},
};

switch (process.env.NODE_ENV_DB_TYPE) {
	case 'mysql':
		module.exports = CommonService_mysql;
		break;
	case 'mongodb':
		module.exports = UserService_mongodb;
		break;
	default:
		module.exports = UserService_mongodb;
}
